import {Component, ElementRef, ViewChild} from '@angular/core';
import {Content, IonicPage, NavController, NavParams, Refresher} from 'ionic-angular';
import {PageSplit} from "../../utils/page/page";
import {BusinessManageService} from "./business-manage.service";
import {AppConfig} from "../../../app/appConfig";

/**
 * Generated class for the BusinessManagePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-business-manage',
  templateUrl: 'business-manage.html',
})
export class BusinessManagePage {
  @ViewChild(Content) content: Content;
  @ViewChild(Refresher) refresher: Refresher;
  private page: PageSplit = {
    pageSize: 10,
    pageNo: 0,
    isLastPage: false
  };

  private dataList: any = [];

  constructor(public navCtrl: NavController, public navParams: NavParams, private manageService: BusinessManageService, private appConfig: AppConfig,) {
  }

  getByPage(refresher?: any) {
    this.page.pageNo++;
    this.manageService.getAllByPage(this.page).subscribe(res => {
      if (refresher) {
        this.refresher.complete();
        this.dataList = [];
      }
      if (res.code === 200) {
        this.dataList = this.dataList.concat(res.data.list);
        this.page.isLastPage = res.data.isLastPage;
      }
      else {
        this.appConfig.presentToast(res.msg);
      }
    });
  }

  deleteRestaurant(id, i) {
    this.manageService.deleteById(id).subscribe(res => {
      if (res.code === 200) {
        this.dataList.splice(i, 1);
      }
      else {
        this.appConfig.presentToast(res.msg);
      }
    })
  }

  doRefresh() {
    this.page = {
      isLastPage: false,
      pageSize: 10,
      pageNo: 0
    };
    this.getByPage(this.refresher);
  }

  doInfinite(infiniteScroll): Promise<any> {
    return new Promise(resolve => {
      let that = this;
      setTimeout(function () {
        if (!that.page.isLastPage) {
          that.getByPage();
          resolve();
        }
        else {
          resolve();
        }
      }, 1000);
    });
  }

  showAddPage() {
    this.navCtrl.push('BusinessAddPage');
  }


  ionViewWillEnter() {
    this.refresher._top = '50px';
    this.refresher.state = 'refreshing';
    this.refresher._beginRefresh();
    // this.doRefresh();
  }

}
